//Flag between part ,question and pool
var flag = true;

/**
 * 
 * Part
 */
// backup part
var backupPart;
var txtPartName = "<input type=\"text\" id=\"txtPart\" class=\"partName form-control txtPartName\"><h5 id=\"partNameError\" class=\"error\"></h5>";
var btnControl = "<a href=\"\" class=\"partUpdate\"> <i"
		+ " class=\"fa fa-check fa-2x\"></i><span class=\"nav-text\">Update</span></a><a "
		+ "href=\"#\" class=\"partCancel\"><i class=\"fa fa-undo fa-2x\"></i><span"
		+ " class=\"nav-text\">Cancel</span></a>";
var flagEditPart = true;
var flagAddPart = true;

/**
 * Choose from Pool
 */
var poolEditTemplate = "<div class=\"choose_pool\" id=\"poolEdit\"><fieldset class=\"input_table\"><legend>From Pool</legend><div class=\"input_row hidden\"><div>Pool ID</div><div><input id=\"questionPoolId\" placeholder=\"ID\" class=\"form-control\" /></div></div><div class=\"input_row\"><div>Name</div><div><h4 id=\"questionPoolName\">Pool Name</h4></div></div><div class=\"input_row\"><div>Number Question</div><div><input id=\"numberQuestion\" placeholder=\"Number question from pool\" class=\"form-control\" value=\"0\" /><h5 id=\"numberError\" class=\"error\"></h5></div></div><div class=\"input_row\"><div></div><div><a href=\"\" id=\"savePool\" class=\"btn btn-primary btn-sm\">Save</a><a href=\"\" id=\"cancelPool\" class=\"btn btn-primary btn-sm\">Cancel</a></div><div></div></div></fieldset></div>";
var btnPoolUpdate = "<a href=\"\" id=\"editPool\" class=\"btn btn-primary btn-sm\">Update</a>";
var poolBackup;
var poolEditBackup;
var poolTemplate = "<div class=\"choose_pool\"><fieldset class=\"input_table\"><legend>From Pool</legend><div class=\"input_row hidden\"><div>Pool ID</div><div><h6 class=\"poolId\"></h6></div></div><div class=\"input_row\"><div><h4>Pool Name:</h4></div><div><h4 class=\"poolName\">Inheritance</h4></div></div><div class=\"input_row\"><div><h4>Question:</h4></div><div><h4 class=\"poolNumber\">5</h4></div></div><div class=\"input_row\"><div></div><div><a href=\"\" class=\"edit\">Edit</a></div></div></fieldset></div>";

var flagEditPool = true;
var flagAddPool = true;

$(document).on("click", ".choosePool", function() {
	if (flag == false) {
		alert("You can modify only Part or Question or Part Info at a time!");
		return false;
	}
	if(flagEditPool == false || flagAddPool == false){
		alert("Can not add or edit part info!");
		return false;
	}
	flagAddPool = false;
	flag = false;
	createPoolPopup();
	return false;
});

$(document).on("click", ".edit", function(){
	if (flag == false) {
		alert("You can modify only Part or Question or Part Info at a time!");
		return false;
	}
	
	if(flagEditPool == false || flagAddPool == false){
		alert("Can not add or edit part info!");
		return false;
	}
	
	flagEditPool = false;
	flag = false;
	
	var partContent = $(this).parents(".part_content");
	var field = $(this).parents(".input_table");
	var poolId = $(this).parents(".choose_pool").find(".poolId").text();
	var poolName = $(this).parents(".choose_pool").find(".poolName").text();
	var poolPoint = $(this).parents(".choose_pool").find(".poolPoint").text();
	var poolNumber = $(this).parents(".choose_pool").find(".poolNumber").text();
	
	//backup wrong
	poolEditBackup = partContent.html();
	partContent.html(poolEditTemplate);
	//Send data
	$("#questionPoolName").text(poolName);
	$("#questionPoolId").val(poolId);
	$("#numberQuestion").val(poolNumber);
	$("#point").val(poolPoint);
	return false;
});

var number = 0;

$(document).on("click", "#savePool", function() {
	
	var id = $("#questionPoolId").val();
	var point = $("#point").val();
	var numberQuestion = $("#numberQuestion").val();
	var testId = $("#testId").text();
	var partId = $(this).parents(".question_part").find(".partId");
	var partName = $(this).parents(".question_part").find(".partName");
	//Validate
	
	$.ajax({
		url: "../../pool/question/"+id,
		type: "GET",
		success: function(data){
			number = data;
			if(!$.isNumeric(numberQuestion) || numberQuestion <1 || numberQuestion > number){
				$("#numberError").text("Please, enter number greater than 0 and less than "+number+"!");
				return false;
			}else{
				$("#numberError").text("");
			}
			
			var requestData = {
					testPartId : id,
					testPartName : partName.text(),
					point: point,
					numberQuestion: numberQuestion
				};
				// Ajax load part
				$.ajax({
					url : '../../' + testId + '/part/editpoolid/' + partId.text(),
					type : 'POST',
					data : JSON.stringify(requestData),
					dataType : 'json',
					contentType : 'application/json; charset=utf-8',
					error : function(xhr) {
						alert('Error: ' + xhr.statusText);
						flagEditPool = true;
						flagAddPool = true;
						flag = true;
					},
					success : function(data) {
						//Show data
						var pool = $("#poolEdit");
						var name = pool.find("#questionPoolName").text();
						var poolData = $(poolTemplate).replaceAll("#poolEdit");
						var poolId = poolData.find(".poolId");
						var poolName = poolData.find(".poolName");
						var poolNumber = poolData.find(".poolNumber");
						var poolPoint = poolData.find(".poolPoint");
						poolId.text(id);
						poolName.text(name);
						poolPoint.text(point);
						poolNumber.text(numberQuestion);
						flagEditPool = true;
						flagAddPool = true;
						flag = true;
					},
					async : true,
					processData : false
				});
				
		},
		error: function(e){
			alert('Error when loading number of question in Pool' + e.statusCode);
			return false;
		}
	});
	return false;
});

$(document).on("click", "#cancelPool", function() {
	var partContent = $(this).parents(".part_content");
	if(flagEditPool == false){
		partContent.html(poolEditBackup);
	}
	
	if(flagAddPool == false){
		partContent.html(poolBackup);
	}
	
	flagEditPool = true;
	flagAddPool = true;
	flag = true;
	return false;
});

/**
 * DialogBox
 */

function createPoolPopup() {
	var poolPopup = $("#pool").dialog({
		modal : true,
		open : function(data) {
			$(this).load("../../pool/lookup");
		},
		buttons : [ {
			text : "OK",
			click : function() {
				//Show pool edit
				var poolEdit = $("#poolEdit").parent();
				poolBackup = poolEdit.html();
				poolEdit.html(poolEditTemplate);
				//Send data
				$("#questionPoolName").text($("#poolName").text());
				$("#questionPoolId").val($("#poolId").text());
				//process before close
				poolPopup.dialog("close");
				return false;
			}
		}, {
			text : "Cancel",
			click : function() {
				flagEditPool = true;
				flagAddPool = true;
				flag = true;
				poolPopup.dialog("close");
				return false;
			}
		} ],
		width : 800,
		title : 'Pool Lookup',
		position : {
			my : 'center center',
			at : 'top+50'
		}
	});
};


//Part
// Get Edit part Test OK
$(document).on("click", ".partEdit", function() {
	if (flag == false) {
		alert("You can modify only Part or Question or Part Info at a time!");
		return false;
	}
	if (flagEditPart == false || flagAddPart == false) {
		alert("Action not allow");
		return false;
	}
	flag = false;
	flagEditPart = false;
	var control = $(this).parent();
	var partId = $(this).parent().siblings().children(".partId");
	var partNum = $(this).parent().siblings().children(".partNum");
	var partName = $(this).parent().siblings().children(".partName");
	backupPart = $(this).parent().parent().html();
	var testId = $("#testId").text();
	var requestData = {
		testPartId : partId.text(),
		testPartName : partName.text()
	};
	// Ajax load part
	$.ajax({
		url : '../../' + testId + '/part/edit/' + partId.text(),
		type : 'GET',
		data : JSON.stringify(requestData),
		dataType : 'json',
		contentType : 'application/json; charset=utf-8',
		error : function(xhr) {
			alert('Error: ' + xhr.statusText);
		},
		success : function(data) {
			partId.text(data.testPartId);
			partName.replaceWith(txtPartName);
			partName = $("#txtPart");
			partName.val(data.testPartName);
			autoArrange();
		},
		async : true,
		processData : false
	});
	control.html(btnControl);
	return false;
});

// Edit part Test OK
$(document).on("click", ".partUpdate", function() {
	//Valid part name
	var partNameError = $("#txtPart").val();
	if(partNameError == ""){
		$("#partNameError").text("Part name can not be blank!");
		return false;
	}else{
		$("#partNameError").text("");
	}
	
	
	var control = $(this).parent();
	var partId = $(this).parent().siblings().children(".partId");
	var partNum = $(this).parent().siblings().children(".partNum");
	var partName = $(this).parent().siblings().children(".partName");
	var partUl = $(this).parent().parent();
	var testId = $("#testId").text();
	var requestData = {
		testPartId : partId.text(),
		testPartName : partName.val()
	};
	// Ajax load part
	$.ajax({
		url : '../../' + testId + '/part/edit/' + partId.text(),
		type : 'POST',
		data : JSON.stringify(requestData),
		dataType : 'json',
		contentType : 'application/json; charset=utf-8',
		error : function(xhr) {
			alert('Error: ' + xhr.statusText);
			partUl.html(backupPart);
		},
		success : function(data) {
			partUl.html(backupPart);
			partUl.children().children(".partName").text(data.testPartName);
			partUl.children().children(".partName").val(data.testPartId);
			autoArrange();
		},
		async : true,
		processData : false
	});
	flagEditPart = true;
	flagAddPart = true;
	flag = true;
	return false;
});

var addPartLine = "<div><a class=\"addNewPart\" href=\"\">Add New Part</a></div>";
var newPart = "<div class=\"question_part\"><div class=\"part_name\"><ul><li><h6 class=\"partId hidden\"></h6><h3 class=\"partNum\">Part I:</h3>"
		+ "<input type=\"text\" class=\"partName form-control txtPartName\" id=\"txtPart\"><h5 id=\"partNameError\" class=\"error\"></h5></li><li class=\"pull-right\">"
		+ "<a class=\"partSave\" href=\"\"> <i class=\"fa fa-check fa-2x\"></i><span class=\"nav-text\">Save</span></a>"
		+ "<a class=\"partCancel\" href=\"#\"><i class=\"fa fa-undo fa-2x\"></i><span class=\"nav-text\">Cancel</span>"
		+ "</a></li></ul></div><div class=\"part_content\">"
		+ "<div class=\"choose_pool\" id=\"poolEdit\"><a class=\"choosePool\" href=\"#\">Choose From Pool</a>"
		+ "<div id=\"pool\" ></div></div>"
		+ "<div class=\"add_question\"><a class=\"addQuestion\" href=\"#\">Add Question</a></div></div></div>";
var choosePoolLine = "<div class=\"add_question\"><a class=\"choosePool\" href=\"#\">Choose From Pool</a></div>";
var btnEditRemove = "<a href=\"\" class=\"partEdit\"> <i"
		+ " class=\"fa fa-wrench fa-2x\"></i><span class=\"nav-text\">Edit</span></a><a "
		+ "href=\"#\" class=\"partRemove\"><i class=\"fa fa-trash fa-2x\"></i><span"
		+ " class=\"nav-text\">Remove</span></a>";
var backupAdd;
// Add new part Test OK
$(document).on("click", ".addNewPart", function() {
	if (flag == false) {
		alert("You can modify only Part or Question or Part Info at a time!");
		return false;
	}
	if (flagEditPart == false || flagAddPart == false) {
		alert("Action not allow");
		return false;
	}
	flag = false;
	flagAddPart = false;
	// Ajax load part
	$(addPartLine).insertAfter($(this).parent());
	$(newPart).insertAfter($(this).parent());
	autoArrange();
	return false;
});

// Test OK
$(document).on(
		"click",
		".partSave",
		function() {
			
			//Valid part name
			var partNameError = $("#txtPart").val();
			if(partNameError == ""){
				$("#partNameError").text("Part name can not be blank!");
				return false;
			}else{
				$("#partNameError").text("");
			}
			
			// Ajax load part
			var partName = $(this).parent().siblings().children(".partName");
			var testId = $("#testId").text();
			var requestData = {
				testPartId : null,
				testPartName : partName.val()
			};
			// Ajax load part
			$.ajax({
				url : '../../' + testId + '/part/add',
				type : 'POST',
				data : JSON.stringify(requestData),
				dataType : 'json',
				contentType : 'application/json; charset=utf-8',
				error : function(xhr) {
					alert('Error: ' + xhr.statusText);
					// Return previous state
				},
				success : function(data) {
					// Show data
					$("#txtPart").siblings(".partId").text(data.testPartId);
					$("#txtPart").parent().siblings().html(btnEditRemove);
					$("#txtPart").replaceWith(
							"<h3 class=\"partName\">" + data.testPartName
									+ "</h3>");
					autoArrange();
				},
				async : true,
				processData : false
			});
			flagEditPart = true;
			flagAddPart = true;
			flag = true;
			return false;
		});

// Cancel in part name Test OK
$(document).on("click", ".partCancel", function() {
	var partUl = $(this).parent().parent();
	if (flagEditPart == false) {// Editing
		partUl.html(backupPart);
	}
	if (flagAddPart == false) {// Adding
		var part = $(this).parent().parent().parent().parent();
		part.next().remove();
		part.remove();
	}
	flagEditPart = true;
	flagAddPart = true;
	flag = true;
	return false;
});


var partDelete;
// Remove in part name Test OK
$(document).on("click", ".partRemove", function() {
	if (flag == false) {
		alert("You can modify only Part or Question or Part Info at a time!");
		return false;
	}
	
	partDelete = $(this);
	$("#dialog-confirm-part").dialog("open");
	return false;
});

/**
 * Question
 * 
 * @param i
 */

// True/False Template
var truefalse = "<div class=\"question\" id=\"edit\">"
		+ "<div class=\"question_type\">"
		+ "<select id=\"qType\" class=\"form-control\" style=\"width: 150px;\""
		+ "onchange=\"changeType()\">"
		+ "<option value=\"1\">True/False</option>"
		+ "<option value=\"2\">Single Choice</option>"
		+ "<option value=\"3\">Multiple Choice</option>"
		+ "</select>"
		+ "</div>"
		+ "<div class=\"question_number\">"
		+ "<ul>"
		+ "<li><h6 class=\"questionId hidden\">JAVA_OOP_002</h6>"
		+ "<h5 class=\"questionNum\">Question 2:</h5></li>"
		+ "<li class=\"pull-right\"><a href=\"#\" class=\"removeQuestion\">Remove</a>"
		+ "</ul>"
		+ "</div>"
		+ "<div class=\"question_name\">"
		+ "<textarea id=\"q_name\" rows=\"5\" cols=\"75\"></textarea><h5 id=\"questionNameError\" class=\"error\"></h5>"
		+ "</div>"
		+ "<table class=\"question_answer\">"
		+ "<tr class=\"answer\">"
		+ "<td><label><input type=\"radio\" name=\"q\" value=\"A\" />A. True</label></td>"
		+ "<td></td>"
		+ "</tr>"
		+ "<tr class=\"answer\">"
		+ "<td><label><input type=\"radio\" name=\"q\" value=\"B\" />B. False</label></td>"
		+ "<td></td>"
		+ "				</tr>"
		+ "			</table>"
		+ "<table class=\"question_answer\">"
		+ "				<tr>"
		+ "<td></td>"
		+ "<td><a href=\"#\" id=\"updateQuestion\" class=\"btn btn-primary btn-sm\""
		+ ">Update</a><a href=\"\" class=\"btn btn-primary btn-sm\""
		+ " id=\"cancelQuestion\">Cancel</a></td>" + "</tr>" + "			</table>"
		+ "		</div>"

// Multiple choice Templete
var multiChoice = "<div class=\"question\" id=\"edit\">"
		+ "<div class=\"question_type\">"
		+ "<select id=\"qType\" class=\"form-control\" style=\"width: 150px;\""
		+ "onchange=\"changeType()\">"
		+ "<option value=\"1\">True/False</option>"
		+ "<option value=\"2\">Single Choice</option>"
		+ "<option value=\"3\">Multiple Choice</option>"
		+ "</select>"
		+ "</div>"
		+ "<div class=\"question_number\">"
		+ "<ul>"
		+ "<li><h6 class=\"questionId hidden\">JAVA_OOP_002</h6>"
		+ "<h5 class=\"questionNum\">Question 2:</h5></li>"
		+ "<li class=\"pull-right\"><a href=\"#\" class=\"removeQuestion\">Remove</a>"
		+ "</ul>"
		+ "</div>"
		+ "<div class=\"question_name\">"
		+ "<textarea id=\"q_name\" rows=\"5\" cols=\"75\"></textarea><h5 id=\"questionNameError\" class=\"error\"></h5>"
		+ "</div>"
		+ "<table class=\"question_answer\">"
		+ "<tr class=\"answer\">"
		+ "<td><label><input type=\"checkbox\" name=\"q\" value=\"A\" />A.</label></td>"
		+ "<td><textarea id=\"A\" rows=\"3\" cols=\"75\"></textarea><h5 id=\"answerA\" class=\"error\"></h5></td>"
		+ "</tr>"
		+ "<tr class=\"answer\">"
		+ "<td><label><input type=\"checkbox\" name=\"q\" value=\"B\" />B.</label></td>"
		+ "<td><textarea id=\"B\" rows=\"3\" cols=\"75\"></textarea><h5 id=\"answerB\" class=\"error\"></h5></td>"
		+ "</tr>"
		+ "<tr class=\"answer\">"
		+ "<td><label><input type=\"checkbox\" name=\"q\" value=\"C\" />C.</label></td>"
		+ "<td><textarea id=\"C\" rows=\"3\" cols=\"75\"></textarea><h5 id=\"answerC\" class=\"error\"></h5></td>"
		+ "</tr>"
		+ "<tr class=\"answer\">"
		+ "<td><label><input type=\"checkbox\" name=\"q\" value=\"D\" />D.</label></td>"
		+ "<td><textarea id=\"D\" rows=\"3\" cols=\"75\"></textarea><h5 id=\"answerD\" class=\"error\"></h5></td>"
		+ "</tr>"
		+ "</table>"
		+ "<table class=\"question_answer\">"
		+ "<tr>"
		+ "<td></td>"
		+ "<td><a href=\"#\""
		+ "onclick=\"javascript:addAnswer(0); return false;\">Add Answer</a></td>"
		+ "</tr>"
		+ "<tr>"
		+ "<td></td>"
		+ "<td><a href=\"#\" id=\"updateQuestion\" class=\"btn btn-primary btn-sm\""
		+ ">Update</a><a href=\"\" class=\"btn btn-primary btn-sm\""
		+ " id=\"cancelQuestion\">Cancel</a></td>" + "</tr>" + "</table>"
		+ "</div>";

// Single choice Template
var singleChoice = "<div class=\"question\" id=\"edit\">"
		+ "<div class=\"question_type\">"
		+ "<select id=\"qType\" class=\"form-control\" style=\"width: 150px;\""
		+ "onchange=\"changeType()\">"
		+ "<option value=\"1\">True/False</option>"
		+ "<option value=\"2\">Single Choice</option>"
		+ "<option value=\"3\">Multiple Choice</option>"
		+ "</select>"
		+ "</div>"
		+ "<div class=\"question_number\">"
		+ "<ul>"
		+ "<li><h6 class=\"questionId hidden\">JAVA_OOP_002</h6>"
		+ "<h5 class=\"questionNum\">Question 2:</h5></li>"
		+ "<li class=\"pull-right\"><a href=\"#\" class=\"removeQuestion\">Remove</a>"
		+ "</ul>"
		+ "</div>"
		+ "<div class=\"question_name\">"
		+ "<textarea id=\"q_name\" rows=\"5\" cols=\"75\"></textarea><h5 id=\"questionNameError\" class=\"error\"></h5>"
		+ "</div>"
		+ "<table class=\"question_answer\">"
		+ "<tr class=\"answer\">"
		+ "<td><label><input type=\"radio\" name=\"q\" value=\"A\" />A.</label></td>"
		+ "<td><textarea id=\"A\" rows=\"3\" cols=\"75\"></textarea><h5 id=\"answerA\" class=\"error\"></h5></td>"
		+ "</tr>"
		+ "<tr class=\"answer\">"
		+ "<td><label><input type=\"radio\" name=\"q\" value=\"B\" />B.</label></td>"
		+ "<td><textarea id=\"B\" rows=\"3\" cols=\"75\"></textarea><h5 id=\"answerB\" class=\"error\"></h5></td>"
		+ "</tr>"
		+ "<tr class=\"answer\">"
		+ "<td><label><input type=\"radio\" name=\"q\" value=\"C\" />C.</label></td>"
		+ "<td><textarea id=\"C\" rows=\"3\" cols=\"75\"></textarea><h5 id=\"answerC\" class=\"error\"></h5></td>"
		+ "</tr>"
		+ "<tr class=\"answer\">"
		+ "<td><label><input type=\"radio\" name=\"q\" value=\"D\" />D.</label></td>"
		+ "<td><textarea id=\"D\" rows=\"3\" cols=\"75\"></textarea><h5 id=\"answerD\" class=\"error\"></h5></td>"
		+ "</tr>"
		+ "</table>"
		+ "<table class=\"question_answer\">"
		+ "<tr>"
		+ "<td></td>"
		+ "<td><a href=\"#\""
		+ "onclick=\"javascript:addAnswer(0); return false;\">Add Answer</a></td>"
		+ "</tr>"
		+ "<tr>"
		+ "<td></td>"
		+ "<td><a href=\"#\" id=\"updateQuestion\" class=\"btn btn-primary btn-sm\""
		+ ">Update</a><a href=\"\" class=\"btn btn-primary btn-sm\""
		+ " id=\"cancelQuestion\">Cancel</a></td>" + "</tr>" + "</table>"
		+ "</div>";

var btnAddQuestion = "<a href=\"\" id=\"addQuestion\" class=\"btn btn-primary btn-sm\">Add</a>";
var lineAddQuestion = "<div class=\"add_question\"><a class=\"addQuestion\" href=\"#\">Add Question</a></div>";

// Backup
var backupEditQuestion;

// Flag add question
var flagEditQuestion = true;
var flagAddQuestion = true;
// Show template for add question when click add question line
$(document).on("click", ".addQuestion", function() {
	if (flag == false) {
		alert("You can modify only Part or Question or Part Info at a time!");
		return false;
	}
	if (flagAddQuestion == false || flagEditQuestion == false) {
		alert("Action not allow");
		return false;
	}
	
	flag = false;
	flagAddQuestion = false;
	var question = $(this).parent();
	$(truefalse + lineAddQuestion).insertAfter(question);
	$("#updateQuestion").replaceWith(btnAddQuestion);
	autoArrange();
	return false;
});

// True false question
var truefalseQuestion = "<div class=\"question\"><div class=\"question_number\"><ul><li><h6 class=\"questionId hidden\">"
		+ "</h6><h5 class=\"questionNum\">Question 2:</h5></li><li class=\"pull-right\"><a class=\"editQuestion\" href=\"\">Edit</a>"
		+ "<a class=\"removeQuestion\" href=\"\">Remove</a></li></ul></div><div class=\"question_name\"></div><div class=\"question_answer\">"
		+ "<div><input type=\"radio\" value=\"A\"disabled>A. True</div><div><input type=\"radio\" value=\"B\" disabled>B. False</div></div></div>";
// Mutil Choice
var multiChoiceQuestion = "<div class=\"question\"><div class=\"question_number\"><ul><li><h6 class=\"questionId hidden\"></h6>"
		+ "<h5 class=\"questionNum\">Question 1:</h5></li><li class=\"pull-right\"><a class=\"editQuestion\" href=\"\">Edit</a>"
		+ "<a class=\"removeQuestion\" href=\"\">Remove</a></li></ul></div><div class=\"question_name\"></div><div class=\"question_answer\">"
		+ "<div><input type=\"checkbox\" value=\"A\" disabled></div><div><input type=\"checkbox\" value=\"B\" disabled></div><div>"
		+ "<input type=\"checkbox\" value=\"C\" disabled></div><div><input type=\"checkbox\" value=\"D\" disabled></div></div></div>";

var singleChoiceQuestion = "<div class=\"question\"><div class=\"question_number\"><ul><li><h6 class=\"questionId hidden\"></h6>"
		+ "<h5 class=\"questionNum\">Question 1:</h5></li><li class=\"pull-right\"><a class=\"editQuestion\" href=\"\">Edit</a>"
		+ "<a class=\"removeQuestion\" href=\"\">Remove</a></li></ul></div><div class=\"question_name\"></div><div class=\"question_answer\">"
		+ "<div><input type=\"radio\" value=\"A\" disabled></div><div><input type=\"radio\" value=\"B\" disabled></div><div>"
		+ "<input type=\"radio\" value=\"C\" disabled></div><div><input type=\"radio\" value=\"D\" disabled></div></div></div>";

// Save when click add new question button
$(document).on("click", "#addQuestion", function() {
	//Validate question
	var error = false;
	
	var question = "";
	var answer = "";
	var rightAnswer = "";
	var point;
	question = $("#q_name").val();
	var type = $("#qType").val();
	// Right Answer
	if (type == 3) {// Checkbox
		var rightAnswers = $("#edit .question_answer input[name=q]:checked");
		rightAnswers.each(function() {
			rightAnswer += $(this).val();
		});
	} else {// Radio
		rightAnswer = $("#edit .question_answer input[name=q]:checked").val();
		if(rightAnswer == undefined){
			rightAnswer = "";
		}
	}
	
	// Answer
	if (type != 1) {
		answer += ("A_" + $("#A").val());
		answer += (";B_" + $("#B").val());
		answer += (";C_" + $("#C").val());
		answer += (";D_" + $("#D").val());
		
		if($("#A").val() == ""){
			$("#answerA").text("Answer can not be blank!");
			error = true;
		}
		else{
			$("#answerA").text("");
		}
		
		if($("#B").val() == ""){
			$("#answerB").text("Answer can not be blank!");
			error = true;
		}
		else{
			$("#answerB").text("");
		}
		
		if($("#C").val() == ""){
			$("#answerC").text("Answer can not be blank!");
			error = true;
		}
		else{
			$("#answerC").text("");
		}
		
		if($("#D").val() == ""){
			$("#answerD").text("Answer can not be blank!");
			error = true;
		}
		else{
			$("#answerD").text("");
		}
	}
	
	//Validate question
	if(question == ""){
		$("#questionNameError").text("Question can not be blank!");
		error = true;
	}else{
		$("#questionNameError").text("");
	}
	
	if(error == true)
		return false;
	else{
		error = false;
	}
	//Right answer Validate
	if(rightAnswer == ""){
		$("#questionNameError").text("Please, choose right answer!");
		return false;
	}else{
		$("#questionNameError").text("");
	}
	// Get point??
	var requestData = {
		questionId : null,
		question : question,
		answer : answer,
		point : 1,
		rightAnswer : rightAnswer,
		type : type
	};
	// Get part of this question
	var questionPart;
	questionPart = $(this).parents(".question_part");
	// Get partId of this question
	var partId;
	partId = questionPart.find(".partId").text();
	var testId = $("#testId").text();
	$.ajax({
		url : '../../' + testId + '/part/' + partId + '/question/add',
		data : JSON.stringify(requestData),
		dataType : 'json',
		contentType : 'application/json; charset=utf-8',
		type : "POST",
		error : function(error) {
			alert(error);
		},
		success : function(data) {
			// Process after add?
			showQuestion(type, data);
			autoArrange();
		},
		async : true,
		processData : false
	});
	flagAddQuestion = true;
	flagEditQuestion = true;
	flag = true;
	autoArrange();
	return false;
});

// Show data after add
function showQuestion(type, data) {
	var question = $("#edit");
	var answer = data.answer.split(";");
	var rightAnswer = data.rightAnswer;

	if (type == 1) {
		// True/False
		question = $(truefalseQuestion).replaceAll("#edit");
		question.find(".questionId").text(data.questionId);
		question.find(".question_name").text(data.question);
		// Show check
		question.find("input[value=" + rightAnswer + "]").prop("checked", true);
		return false;
	} else if (type == 2) {
		// Single Choice
		question = $(singleChoiceQuestion).replaceAll("#edit");
		question.find("input[value=A]").parent().html(
				"<input type=\"radio\" value=\"A\" disabled>"
						+ answer[0].substring(2, answer[0].length));
		question.find("input[value=B]").parent().html(
				"<input type=\"radio\" value=\"B\" disabled>"
						+ answer[1].substring(2, answer[1].length));
		question.find("input[value=C]").parent().html(
				"<input type=\"radio\" value=\"C\" disabled>"
						+ answer[2].substring(2, answer[2].length));
		question.find("input[value=D]").parent().html(
				"<input type=\"radio\" value=\"D\" disabled>"
						+ answer[3].substring(2, answer[3].length));
	} else {
		// Multi Choice
		question = $(multiChoiceQuestion).replaceAll("#edit");
		question.find("input[value=A]").parent().html(
				"<input type=\"checkbox\" value=\"A\" disabled>"
						+ answer[0].substring(2, answer[0].length));
		question.find("input[value=B]").parent().html(
				"<input type=\"checkbox\" value=\"B\" disabled>"
						+ answer[1].substring(2, answer[1].length));
		question.find("input[value=C]").parent().html(
				"<input type=\"checkbox\" value=\"C\" disabled>"
						+ answer[2].substring(2, answer[2].length));
		question.find("input[value=D]").parent().html(
				"<input type=\"checkbox\" value=\"D\" disabled>"
						+ answer[3].substring(2, answer[3].length));
	}
	question.find(".questionId").text(data.questionId);
	question.find(".question_name").text(data.question);
	// Selected
	for (var i = 0; i < rightAnswer.length; i++) {
		question.find("input[value=" + rightAnswer[i] + "]").prop("checked",
				true);
	}
	autoArrange();
	return false;
}

// Edit when click edit question
$(document).on(
		"click",
		".editQuestion",
		function() {
			// Get question id;
			if (flag == false) {
				alert("Action not allow");
				return false;
			}
			if (flagAddQuestion == false || flagEditQuestion == false) {
				alert("Action not allow");
				return false;
			}
			flag = false;
			flagEditQuestion = false;
			var question = $(this).parents(".question");
			var questionId = question.find(".questionId").text();
			// Using ajax get Server question
			$.ajax({
				url : '../../noTestId/part/noPartId/question/' + questionId,
				type : "GET",
				dataType : "json",
				contentType : "application/json; charset=utf-8",
				error : function(error) {
					alert(error + "Error No Processing");
				},
				success : function(data) {
					backupEditQuestion = question.clone();
					var answer = data.answer.split(";");
					if (data.type == 1) {
						question.replaceWith(truefalse);
					} else if (data.type == 2) {
						question.replaceWith(singleChoice);
					} else {
						question.replaceWith(multiChoice);
					}

					$("#q_name").val(data.question);
					$("#qType").val(data.type);
					$("#qType").prop("disabled", true);
					$("#edit").find(".questionId").text(questionId);

					// Show database
					if (data.type == 1) {
						// set true or false
					} else {
						$("#A").val(answer[0].substring(2, answer[0].length));
						$("#B").val(answer[1].substring(2, answer[1].length));
						$("#C").val(answer[2].substring(2, answer[2].length));
						$("#D").val(answer[3].substring(2, answer[3].length));
					}
					// Set old right Answer
					if (data.type != 1) {
						for (var i = 0; i < data.rightAnswer.length; i++) {
							$("#" + data.rightAnswer[i]).parent().siblings()
									.find("input").prop("checked", true);
						}
					} else {// True false
						$("#edit")
								.find("input[value=" + data.rightAnswer + "]")
								.prop("checked", true);
					}
					autoArrange();
				}
			});
			autoArrange();
			return false;
		});

// Update when click update in edit action
$(document).on("click", "#updateQuestion", function() {
	//Validate
	var error = false;
	
	var question = "";
	var answer = "";
	var rightAnswer = "";
	var point;

	question = $("#q_name").val()
	var type = $("#qType").val();
	// Right Answer
	if (type == 3) {// Checkbox
		var rightAnswers = $("#edit .question_answer input[name=q]:checked");
		rightAnswers.each(function() {
			rightAnswer += $(this).val();
		});
	} else {// Radio
		rightAnswer = $("#edit .question_answer input[name=q]:checked").val();
		if(rightAnswer == undefined){
			rightAnser = "";
		}
	}

	// Answer
	if (type != 1) {
		answer += ("A_" + $("#A").val());
		answer += (";B_" + $("#B").val());
		answer += (";C_" + $("#C").val());
		answer += (";D_" + $("#D").val());
		
		if($("#A").val() == ""){
			$("#answerA").text("Answer can not be blank!");
			error = true;
		}
		else{
			$("#answerA").text("");
		}
		
		if($("#B").val() == ""){
			$("#answerB").text("Answer can not be blank!");
			error = true;
		}
		else{
			$("#answerB").text("");
		}
		
		if($("#C").val() == ""){
			$("#answerC").text("Answer can not be blank!");
			error = true;
		}
		else{
			$("#answerC").text("");
		}
		
		if($("#D").val() == ""){
			$("#answerD").text("Answer can not be blank!");
			error = true;
		}
		else{
			$("#answerD").text("");
		}
	}
	
	//Validate question
	if(question == ""){
		$("#questionNameError").text("Question can not be blank!");
		error = true;
	}else{
		$("#questionNameError").text("");
	}
	
	if(error == true)
		return false;
	else{
		error = false;
	}
	
	//Right answer Validate
	if(rightAnswer == ""){
		$("#questionNameError").text("Please, choose right answer!");
		return false;
	}else{
		$("#questionNameError").text("");
	}
	
	// Get question id
	var questionId = $("#edit").find(".questionId").text();
	// Get point??
	var requestData = {
		questionId : questionId,
		question : question,
		answer : answer,
		point : 1,
		rightAnswer : rightAnswer,
		type : type
	};

	$.ajax({
		url : '../../noTestId/part/noPartId/question/edit/' + questionId,
		data : JSON.stringify(requestData),
		dataType : 'json',
		contentType : 'application/json; charset=utf-8',
		type : "POST",
		error : function(error) {
			alert(error);
		},
		success : function(data) {
			showQuestion(type, data);
			autoArrange();
		},
		async : true,
		processData : false
	});
	// Process after update?
	flagAddQuestion = true;
	flagEditQuestion = true;
	flag = true;
	autoArrange();
	return false;
});

var deleteQuestion;

// Remove question
$(document).on("click", ".removeQuestion", function() {
	deleteQuestion = $(this).parents(".question");
	$("#dialog-confirm").dialog("open");
	return false;
});

// Cancel
$(document).on("click", "#cancelQuestion", function() {
	var question = $("#edit");
	var lineAddQuestion = question.next();
	if (flagAddQuestion == false) {
		// just remove new question
		question.remove();
		lineAddQuestion.remove();
	} else {
		// backup to previous state
		question.replaceWith(backupEditQuestion);
		// lineAddQuestion.remove();
	}
	autoArrange();
	flagAddQuestion = true;
	flagEditQuestion = true;
	flag = true;
	return false;
});

$(document).on("change", "#qType", function() {
	var question = $("#edit");
	var type = $("#qType").val();
	if (type == 1) {
		question.replaceWith(truefalse);
	} else if (type == 2) {
		question.replaceWith(singleChoice);
	} else {
		question.replaceWith(multiChoice);
	}
	try {
		$("#updateQuestion").replaceWith(btnAddQuestion);
	} catch (e) {

	}
	$("#qType").val(type);
	autoArrange();
	return false;
});

$(document).ready(function(){
	autoArrange();
});

function autoArrange(){
	var parts = $("#main_content").find(".question_part");
	for(var i = 0; i < parts.length; i++){
		var part = $(".question_part:eq("+i+")");
		var partNum = part.find(".partNum");
		partNum.text("Part " + (i+1) +":");
		//Arrange question in part
		var questions = $(".question_part:eq("+i+") .question");	
		
		for(var j = 0; j< questions.length; j++){
			var question = $(".question:eq("+j+")");
			var questionNum = question.find(".questionNum");
			questionNum.text("Question " + (j+1) +":");
		}
	}
};


//Delete Question
$(document).ready(function() {
	createDialogConfirm();
	createDialogConfirmPart();
	createDialogAlert();
	createDialogOk();
});

function createDialogConfirmPart() {
	$("#dialog-confirm-part").dialog({
		autoOpen : false,
		resizable : false,
		modal : true,
		buttons : {
			"Delete" : function() {
				var partId = partDelete.parent().siblings().children(".partId");
				var part = partDelete.parent().parent().parent().parent();
				var testId = $("#testId").text();
				$.ajax({
					url : '../../' + testId + '/part/delete/' + partId.text(),
					type : 'GET',
					error : function(xhr) {
						alert('Error: ' + xhr.statusText);
						flag = true;
						$("#dialog-alert").dialog("open");
					},
					success : function(data) {
						part.next().remove();
						part.remove();
						autoArrange();
						flag = true;
						$("#dialog-ok").dialog("open");
					},
					async : true,
					processData : false
				});
				$(this).dialog("close");
			},
			Cancel : function() {
				$(this).dialog("close");
			}
		}
	});
};

function createDialogConfirm() {
	var testId = $("#testId").text();
	var testName = $("#testName").text();
	$("#dialog-confirm").dialog({
		autoOpen : false,
		resizable : false,
		modal : true,
		buttons : {
			"Delete" : function() {
				var question = deleteQuestion;
				var questionId = question.find(".questionId").text();
				var lineAddQuestion;
				// just remove html when add new question
				if (flagAddQuestion == false) {
					// Remove html but not call controller
					lineAddQuestion = question.next();
					question.remove();
					lineAddQuestion.remove();
					flagAddQuestion = true;
					flagEditQuestion = true;
					flag = true;
					return false;
				} else {
					$.ajax({
						url : '../../noTestId/part/noPartId/question/delete/' + questionId,
						type : "GET",
						error : function(jqXHR, textStatus, errorThrown) {
							$("#dialog-alert").dialog("open");
							return false;
						},
						success : function(data) {
							if (data == "OK") {
								// Remove when #edit is avaiable
								if (flagEditQuestion == false) {
									lineAddQuestion = question.next();
									lineAddQuestion.remove();
									question.remove();
								} else {
									question.next().remove(); // Remove line add
									// question after
									// question
									question.remove();// remove question
								}
								flagAddQuestion = true;
								flagEditQuestion = true;
								flag = true;
								$("#dialog-ok").dialog("open");
								autoArrange();
							} else
								alert("Error");
							return false;
						},
					});
				}
				$(this).dialog("close");
			},
			Cancel : function() {
				$(this).dialog("close");
			}
		}
	});
};
function createDialogAlert() {
	$("#dialog-alert").dialog({
		autoOpen : false,
		resizable : false,
		modal : true,
		buttons : {
			OK : function() {
				$(this).dialog("close");
			}
		}
	});
};

function createDialogOk() {
	$("#dialog-ok").dialog({
		autoOpen : false,
		resizable : false,
		modal : true,
		buttons : {
			OK : function() {
				$(this).dialog("close");
			}
		}
	});
};
